package com.gameapplet.webchatapplogin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gameapplet.util.Base64Util;
import com.gameapplet.util.HttpTookit;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.*;
@Controller
@RequestMapping("/wxlogin")
public class WebChatController {
    final static String AppID = "wxfffb2a6c993b2249";
    final static String Secret = "234b4b49ee25a9415b5f64e825191d4f";
    @RequestMapping(value="/getsessionkey",method = RequestMethod.POST)
    public  String getSessionKeyOropenid(@RequestBody String code){

        //微信端登录code值
       JSONObject ResultJson =JSONObject.parseObject(code);
         String JsCode = ResultJson.getString("code");
       // Locale locale = new Locale("en", "US");
        //ResourceBundle resource = ResourceBundle.getBundle("config/wx-config",locale);   //读取属性文件
         String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code".replace("APPID",AppID).replace("SECRET",Secret).replace("JSCODE",JsCode);  //请求地址 https://api.weixin.qq.com/sns/jscode2session
//        Map<String, String> requestUrlParam = new HashMap<String, String>();
         String openIdResult = HttpTookit.doGet(requestUrl, null);
//        requestUrlParam.put("appid", "wxfffb2a6c993b2249");  //开发者设置中的appId
//        requestUrlParam.put("secret", "77e2062054eab5c9bf23c1e024c29ae0"); //开发者设置中的appSecret
//        requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
//        requestUrlParam.put("grant_type", "authorization_code");    //默认参数 authorization_code

        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
//        JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
//        System.out.println(jsonObject);
        JSONObject openIdResultJson = JSONObject.parseObject(openIdResult);

        return "redirect:ControllerB";
    }

//    @RequestMapping(value="/getWxUserInfo",method = RequestMethod.POST)
//    @ResponseBody
//    public static JSONObject getUserInfo(String encryptedData, String sessionKey, String iv)throws Exception {
//        // 被加密的数据
//        byte[] dataByte = Base64Util.decodeByte(encryptedData);
//        // 加密秘钥
//        byte[] keyByte = Base64Util.decodeByte(sessionKey);
//        // 偏移量
//        byte[] ivByte = Base64Util.decodeByte(iv);
//        try {
//
//            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
//            int base = 16;
//            if (keyByte.length % base != 0) {
//                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
//                byte[] temp = new byte[groups * base];
//                Arrays.fill(temp, (byte) 0);
//                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
//                keyByte = temp;
//            }
//            // 初始化
//            Security.addProvider(new BouncyCastleProvider());
//            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
//            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
//            parameters.init(new IvParameterSpec(ivByte));
//            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//            byte[] resultByte = cipher.doFinal(dataByte);
//            if (null != resultByte && resultByte.length > 0) {
//                String result = new String(resultByte, "UTF-8");
//                JSONObject UserInfoResultJson = JSONObject.parseObject(result);
//          if() {
//              UserInfoResultJson.getString("openid");
//              UserInfoResultJson.getString("nickname");
//              UserInfoResultJson.getString("avanturl");
//              UserInfoResultJson.getString("country");
//          }
//                return JSON.parseObject(result);
//            }
//        } catch (NoSuchAlgorithmException e){
//            e.printStackTrace();
//            //
//        } catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//           //
//        } catch (InvalidParameterSpecException e) {
//            e.printStackTrace();
//          //
//        } catch (IllegalBlockSizeException e) {
//            e.printStackTrace();
//            //
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
//           //
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
////            log.error(e.getMessage(), e);
//        } catch (InvalidKeyException e) {
//            e.printStackTrace();
////            log.error(e.getMessage(), e);
//        } catch (InvalidAlgorithmParameterException e) {
//            e.printStackTrace();
////            log.error(e.getMessage(), e);
//        } catch (NoSuchProviderException e) {
//            e.printStackTrace();
////            log.error(e.getMessage(), e);
//        }
//        return null;
//    }


}
